package com.huawei.struts.util;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class PageUtil extends HibernateDaoSupport {
	
	/**
	 * 得到数据的总数
	 * @param hql
	 * @return
	 */
	public int getAllRowCount(String hql) {
		return getHibernateTemplate().find(hql).size();
	}
	
	
	public List queryForPage1(final String hql, final int offset,
			final int length) {
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				query.setFirstResult(offset);
				query.setMaxResults(length);
				List list = query.list();
				return list;
			}
		});
		return list;
	}
	
	
	public  PageBean queryForPage(String hql,PageBean pageBean) {
		 
		// 查询语句
		int allRow = this.getAllRowCount(hql);
		int pageSize=pageBean.getPageSize();
		int currentPage=pageBean.getCurrentPage();
		// 总记录数
		int totalPage = PageBean.countTotalPage(pageSize, allRow);
		
		// 总页数
		final int offset = PageBean.countOffset(pageSize, currentPage, totalPage);
		// 当前页开始记录
		final int length = pageSize;
		// 每页记录数
		List list = this.queryForPage1(hql, offset, length);
		
		// 把分页信息保存到bean中
		PageBean pageBean1 = new PageBean();
		pageBean1.setPageSize(pageSize);
		pageBean1.setCurrentPage(PageBean.CorrectCurrentPage(currentPage, totalPage));
		pageBean1.setAllRow(allRow);
		pageBean1.setTotalPage(totalPage);
		pageBean1.setList(list);
		pageBean1.setUpPage(PageBean.CorrectCurrentPage(currentPage, totalPage)-1);
		pageBean1.setDownPage(PageBean.CorrectCurrentPage(currentPage, totalPage)+1);
		return pageBean1;
	}

}
